package com.juicygames.framework.android;

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.juicygames.undoer.world.World;

public class AndroidGameView extends SurfaceView implements SurfaceHolder.Callback {
	private static final String LOGTAG = AndroidGameView.class.getName();

	private Context context;
	private AndroidGame game;
	private GameThread gameThread;

	public AndroidGameView(Context context, AttributeSet attrs) {
		super(context, attrs);
		
		this.context = context;

		SurfaceHolder surfaceHolder = getHolder();
		surfaceHolder.addCallback(this);
		gameThread = new GameThread(surfaceHolder);
	}

	public void setGame(World game) {
		this.game = game;
		game.load(context);
		gameThread.setGame(game);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent msg) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return false;
		}
		
		synchronized (game) {
			game.onKeyDown(keyCode);
			return true;
		}
	}
  
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent msg) {
		synchronized (game) {
			game.onKeyUp(keyCode);
			return true;
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		synchronized (game) {
			game.onTouch(event);
		}
		return true;
	}

	public void surfaceCreated(SurfaceHolder holder) {
		gameThread.start();
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		boolean retry = true;
		gameThread.halt();
		while (retry) {
			try {
				gameThread.join();
				retry = false;
			} catch (InterruptedException e) {}
		}
	}
	
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
}
